package com.luoran.bartalks.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFHyperlink;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Hyperlink;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.beetl.sql.core.engine.PageQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BarcodeQRCode;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.luoran.bartalks.action.vo.MaterialMoveVo;
import com.luoran.bartalks.action.vo.PackingListMaterielOfExportVo;
import com.luoran.bartalks.core.UserContext;
import com.luoran.bartalks.core.ext.Pageable;
import com.luoran.bartalks.entity.BaseInfo;
import com.luoran.bartalks.entity.biz.BtMateriel;
import com.luoran.bartalks.entity.biz.BtPackingList;
import com.luoran.bartalks.entity.biz.BtPackingListMateriel;
import com.luoran.bartalks.entity.biz.BtPlanDetails;
import com.luoran.bartalks.entity.biz.BtRuleRecord;
import com.luoran.bartalks.service.IBtMaterielMoveService;
import com.luoran.bartalks.service.IBtMaterielService;
import com.luoran.bartalks.service.IBtPackingListMaterielService;
import com.luoran.bartalks.service.IBtPackingListService;
import com.luoran.bartalks.service.IBtPlanDetailsService;
import com.luoran.bartalks.service.IBtRuleRecordService;
import com.luoran.bartalks.utils.EnumMaterielMoveColumnName;
import com.luoran.bartalks.utils.EnumPackingListColumnName;
import com.luoran.bartalks.utils.EnumPackingListMaterielColumnName;
import com.luoran.bartalks.utils.EnumRuleRecordColumnName;
import com.luoran.bartalks.utils.EnumScanType;
import com.luoran.bartalks.utils.ExcelWriteImgUtil;
import com.luoran.bartalks.utils.UUID;

/**
 * 箱单物料关系的Controller
 * 
 * @author wmm 2018年1月11日 下午5:34:56
 */
@RequestMapping("/packingListMateriel")
@Controller
public class BtPackingListMaterielAction implements Pageable {
	private static final Logger log = LoggerFactory.getLogger(BtPackingListMaterielAction.class);
	@Autowired
	private IBtPackingListMaterielService packingListMaterielService;

	@Autowired
	private IBtMaterielService materielService;

	@Autowired
	private IBtPackingListService packingListService;

	@Autowired
	private IBtPlanDetailsService planDetailsService;

	@Autowired
	private IBtRuleRecordService ruleRecordService;

	@Autowired
	private IBtMaterielMoveService materielMoveService;

	@RequestMapping
	public String lookMateriel() {
		return "projectPlanManage/addProject";
	}

	/**
	 * PDF导出. id是箱单id
	 * 
	 * @param packingListId
	 * @param req
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("/exportPDF/{id}")
	@ResponseBody
	public JSONObject generatePDF(@PathVariable("id") String packingListId, HttpServletRequest req)
			throws UnsupportedEncodingException {
		JSONObject result = new JSONObject();
		// 根据箱单id查询箱单信息
		BtPackingList packingList = packingListService.lookPackingList(packingListId);
		// 根据箱单id查询含有的物料关系
		List<BtPackingListMateriel> PackingListMateriel = packingListMaterielService
				.getMaterielsByPackingListId(packingListId);
		// 1.新建PDF的document对象
		Document document = new Document();
		// 2.建立一个书写器(Writer)与document对象关联，通过书写器(Writer)可以将文档写入到磁盘中。
		// 创建 PdfWriter 对象 第一个参数是对文档对象的引用，第二个参数是文件的实际名称，在该名称中还会给出其输出路径。
		PdfWriter writer = null;
		try {
			writer = PdfWriter.getInstance(document,
					new FileOutputStream(this.getClass().getResource("materiel.pdf").getPath()));
		} catch (FileNotFoundException | DocumentException e) {
			e.printStackTrace();
		}
		// 3.打开文档
		document.open();
		// 中文字体,解决中文不能显示问题
		BaseFont bfChinese = null;
		try {
			bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
		} catch (DocumentException | IOException e) {
			e.printStackTrace();
		}
		// 接收图片
		Image img = null;
		BarcodeQRCode qrcode = null;
		// 4.添加内容段落
		try {
			document.add(new Paragraph("箱单编码" + packingList.getPackingListCode(), new Font(bfChinese)));
			// 生成二维码
			qrcode = new BarcodeQRCode(packingList.getPackingListCode(), 150, 150, null);
			img = qrcode.getImage();
			document.add(img);
			document.add(new Paragraph("包含物料二维码列表如下", new Font(bfChinese)));
			for (BtPackingListMateriel packingListMateriel : PackingListMateriel) {
				qrcode = new BarcodeQRCode(packingListMateriel.getMaterielQrcode(), 150, 150, null);
				img = qrcode.getImage();
				document.add(img);
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		// 5.关闭文档
		document.close();
		// 关闭书写器
		writer.close();
		result.put("flag", true);
		result.put("msg", "ok");
		return result;

	}

	/**
	 * 箱单物料pdf报表下载
	 * 
	 * @param fileName
	 * @param res
	 */
	@GetMapping("/download")
	public void downloadFile(String fileName, HttpServletResponse res) {
		InputStream fis = this.getClass().getResourceAsStream(fileName);
		if (fis == null) {
			try {
				res.setContentType("text/html;charset=utf-8");
				res.getWriter().write("模板资源不存在,请联系管理员!");
				res.flushBuffer();
			} catch (IOException e) {
			}
			return;
		}
		res.setContentType("application/pdf");
		try {
			res.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
		} catch (UnsupportedEncodingException e) {
		}
		try {
			IOUtils.copy(fis, res.getOutputStream());
			res.flushBuffer();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
				}
			}
		}
	}

	/**
	 * 箱单报表导出
	 * 
	 * @param req
	 * @param res
	 * @throws IOException
	 */
	@GetMapping("/export/{id}")
	public void export(@PathVariable("id") String packingListId, HttpServletRequest req, HttpServletResponse res)
			throws IOException {
		String fileName = "箱单物料报表" + new SimpleDateFormat("yyyy-MM-dd").format(new Date());
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		try {
			createWorkBook(packingListId).write(os);
		} catch (IOException e) {
			e.printStackTrace();
			log.info("生成Excel错误");
			return;
		} catch (Exception e) {
			e.printStackTrace();
			log.info(e.getMessage());
		}
		byte[] content = os.toByteArray();
		InputStream is = new ByteArrayInputStream(content);
		// 设置response参数
		res.reset();
		res.setContentType("application/vnd.ms-excel;charset=utf-8");
		res.setHeader("Content-Disposition",
				"attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
		ServletOutputStream out = res.getOutputStream();
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(out);
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (final IOException e) {
			throw e;
		} finally {
			if (bis != null)
				bis.close();
			if (bos != null)
				bos.close();
		}
	}

	// 创建excel
	public HSSFWorkbook createWorkBook(String packingListId) throws Exception {
		log.info("创建excel");
		// 创建excel工作簿
		HSSFWorkbook workbook = new HSSFWorkbook();
		// 创建工作表sheet
		HSSFSheet sheet = workbook.createSheet("列表");
		// 单元格格式(用于标题)
		HSSFCellStyle csm = workbook.createCellStyle();
		HSSFFont ft = workbook.createFont();
		ft.setFontName("宋体");
		ft.setFontHeightInPoints((short) 16);
		ft.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 加粗
		csm.setFont(ft);
		csm.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
		csm.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
		csm.setLocked(true);
		csm.setWrapText(true);// 自动换行
		// 背景色
		csm.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		csm.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);

		// 单元格格式(用于列名)
		HSSFCellStyle csdt = workbook.createCellStyle();
		HSSFFont fdt = workbook.createFont();
		fdt.setFontName("微软雅黑");
		fdt.setFontHeightInPoints((short) 10);
		fdt.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 加粗
		csdt.setFont(fdt);
		csdt.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
		csdt.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
		csdt.setLocked(true);
		csdt.setWrapText(true);// 自动换行

		// 单元格格式(用于列表)
		HSSFCellStyle csdd = workbook.createCellStyle();
		HSSFFont fdd = workbook.createFont();
		fdd.setFontName("微软雅黑");
		fdd.setFontHeightInPoints((short) 8);
		fdd.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
		csdd.setFont(fdd);
		csdd.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
		csdd.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
		csdd.setLocked(false);
		csdd.setWrapText(true);// 自动换行

		// 设置为超链接的样式
		HSSFCellStyle linkStyle = workbook.createCellStyle();
		HSSFFont cellFont = workbook.createFont();
		cellFont.setUnderline((byte) 1);
		cellFont.setColor(HSSFColor.BLUE.index);
		linkStyle.setFont(cellFont);

		BtPackingList packingListInfo = packingListService.lookPackingList(packingListId);
		String mainInfo = "";
		if (packingListInfo != null) {
			mainInfo = "公司:" + UserContext.get().getCompanyName();
			BtPlanDetails planInfo = planDetailsService.getItemById(packingListInfo.getPlanId());
			if (planInfo != null) {
				mainInfo = mainInfo + " 项目名称:" + planInfo.getProjectName() + " 计划编码:" + planInfo.getPlanCode();
			} else {
				throw new Exception("数据错误,无" + packingListInfo.getPlanId() + "该计划信息");
			}
			mainInfo = mainInfo + " --- 箱单物料报表";
		} else {
			throw new Exception("数据错误,无" + packingListId + "该箱单信息");
		}
		// 创建第一行，并设置其单元格格式
		HSSFRow rowTitle = sheet.createRow((short) 0);
		rowTitle.setHeight((short) 500);
		sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 13)); // 合并单元格 1：开始行 2：结束行 3：开始列 4：结束列
		HSSFCell cellTitle = rowTitle.createCell(0);
		cellTitle.setCellValue(mainInfo);
		cellTitle.setCellStyle(csm);
		// 箱单信息
		HSSFRow packingListRowTitle = sheet.createRow((short) 1);
		packingListRowTitle.setHeight((short) 300);
		for (int x = 0; x < 10; x++) {
			HSSFCell cell = packingListRowTitle.createCell(x);
			// 设置单元格的内容
			cell.setCellValue(EnumPackingListColumnName.getColumnName(x));
			cell.setCellStyle(csdt);
			sheet.setColumnWidth(x, EnumPackingListColumnName.getColumnName(x).getBytes().length * 2 * 256);
		}
		HSSFRow packingListRowData = sheet.createRow((short) 2);
		packingListRowData.setHeight((short) 300);
		for (int x = 0; x < 10; x++) {
			HSSFCell cell = packingListRowData.createCell(x);
			cell.setCellValue(EnumPackingListColumnName.getMethod(x, packingListInfo));
			cell.setCellStyle(csdd);
			sheet.setColumnWidth(x,
					EnumPackingListColumnName.getMethod(x, packingListInfo).getBytes().length * 2 * 256);
		}

		// 物料信息
		HSSFRow materielRowTitle = sheet.createRow((short) 3);
		materielRowTitle.setHeight((short) 300);
		for (int x = 0; x < 14; x++) {
			// 设置单元格的内容
			HSSFCell cell = materielRowTitle.createCell(x);
			cell.setCellStyle(csdt);
			if (x == 12) {
				cell.setCellValue("打尺记录");
				sheet.autoSizeColumn(x);
			} else if (x == 13) {
				cell.setCellValue("业务记录");
				sheet.autoSizeColumn(x);
			} else {
				cell.setCellValue(EnumPackingListMaterielColumnName.getColumnName(x));
				sheet.setColumnWidth(x, EnumPackingListMaterielColumnName.getColumnName(x).getBytes().length * 2 * 256);
			}

		}

		List<PackingListMaterielOfExportVo> packingListMateriels = packingListMaterielService
				.getMaterielsByPackingListIdOfExport(packingListId);
		for (int i = 0; i < packingListMateriels.size(); i++) {
			HSSFRow materielRowData = sheet.createRow((short) i + 4);
			materielRowData.setHeight((short) 300);
			for (int x = 0; x < 14; x++) {
				HSSFCell cell = materielRowData.createCell(x);
				cell.setCellStyle(csdd);
				if (x == 12) {
					// 获取打尺记录
					List<BtRuleRecord> ruleRecord = ruleRecordService
							.getRuleRecord(packingListMateriels.get(i).getId());
					if (ruleRecord == null||ruleRecord.isEmpty()) {
						cell.setCellValue("无");
					} else {
						cell.setCellValue("打尺记录");
						String sheetName = packingListMateriels.get(i).getCode().length() >= 25
								? packingListMateriels.get(i).getCode().substring(0, 24) + "_"+i
								: packingListMateriels.get(i).getCode()+"_"+i + "的打尺记录";
						Hyperlink hyperlink = new HSSFHyperlink(Hyperlink.LINK_DOCUMENT);
						String sheetNameReplace = ExcelWriteImgUtil.sheetNameReplace(sheetName);
						// 创建打尺记录sheet
						HSSFSheet rulerSheet = workbook.createSheet(sheetNameReplace);
						hyperlink.setAddress(sheetNameReplace + "!A1");
						cell.setHyperlink(hyperlink);
						cell.setCellStyle(linkStyle);
						// 创建第一行主信息，并设置其单元格格式
						HSSFRow rowRuleRecordMain = rulerSheet.createRow((short) 0);
						rowRuleRecordMain.setHeight((short) 500);
						rulerSheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 9)); // 合并单元格 1：开始行 2：结束行 3：开始列 4：结束列
						HSSFCell cellRuleRecordMain = rowRuleRecordMain.createCell(0);
						cellRuleRecordMain.setCellValue(" 物料编码:" + packingListMateriels.get(i).getCode() + " 物料名称:"
								+ packingListMateriels.get(i).getName() + " --- 打尺记录报表");
						cellRuleRecordMain.setCellStyle(csm);
						// 创建第二行列头，并设置其单元格格式
						HSSFRow rowRuleRecordTitle = rulerSheet.createRow((short) 1);
						rowRuleRecordTitle.setHeight((short) 300);
						for (int k = 0; k < 10; k++) {
							HSSFCell cellRuleRecordTitle = rowRuleRecordTitle.createCell(k);
							cellRuleRecordTitle.setCellStyle(csdt);
							cellRuleRecordTitle.setCellValue(EnumRuleRecordColumnName.getColumnName(k));
							rulerSheet.setColumnWidth(k,
									EnumRuleRecordColumnName.getColumnName(x).getBytes().length * 2 * 256);

						}
						// 创建数据列表，并设置其单元格格式
						for (int j = 0; j < ruleRecord.size(); j++) {
							HSSFRow rowRuleRecordData = rulerSheet.createRow((short) j + 2);
							rowRuleRecordData.setHeight((short) 300);
							for (int k = 0; k < 10; k++) {
								HSSFCell cellRuleRecordData = rowRuleRecordData.createCell(k);
								cellRuleRecordData
										.setCellValue(EnumRuleRecordColumnName.getMethod(k, ruleRecord.get(j)));
								cellRuleRecordData.setCellStyle(csdd);
								rulerSheet.setColumnWidth(k,
										EnumRuleRecordColumnName.getMethod(k, ruleRecord.get(j)).getBytes().length * 2
												* 256);
							}

						}
					}
					sheet.autoSizeColumn(x);
				} else if (x == 13) {
					// 获取业务记录
					List<MaterialMoveVo> materialMoves = materielMoveService
							.queryMaterialMoveByPackingListMaterielId(packingListMateriels.get(i).getId());
					if (materialMoves == null||materialMoves.isEmpty()) {
						cell.setCellValue("无");
					} else {
						cell.setCellValue("业务记录");
						String sheetName = packingListMateriels.get(i).getCode().length() >= 25
								? packingListMateriels.get(i).getCode().substring(0, 24) + "_"+i
								: packingListMateriels.get(i).getCode()+ "_"+i + "的业务记录";
						String sheetNameReplace = ExcelWriteImgUtil.sheetNameReplace(sheetName);
						Hyperlink hyperlink = new HSSFHyperlink(Hyperlink.LINK_DOCUMENT);
						// 创建业务记录sheet
						HSSFSheet moveSheet = workbook.createSheet(sheetNameReplace);
						hyperlink.setAddress(sheetNameReplace + "!A1");
						cell.setHyperlink(hyperlink);
						cell.setCellStyle(linkStyle);
						// 创建第一行主信息，并设置其单元格格式
						HSSFRow rowMaterialMoveMain = moveSheet.createRow((short) 0);
						rowMaterialMoveMain.setHeight((short) 500);
						moveSheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 5)); // 合并单元格 1：开始行 2：结束行 3：开始列 4：结束列
						HSSFCell cellMaterialMoveMain = rowMaterialMoveMain.createCell(0);
						cellMaterialMoveMain.setCellValue(" 物料编码:" + packingListMateriels.get(i).getCode() + " 物料名称:"
								+ packingListMateriels.get(i).getName() + " --- 业务记录报表");
						cellMaterialMoveMain.setCellStyle(csm);
						// 创建第二行列头，并设置其单元格格式
						HSSFRow rowMaterialMoveTitle = moveSheet.createRow((short) 1);
						rowMaterialMoveTitle.setHeight((short) 300);
						for (int k = 0; k < 5; k++) {
							HSSFCell cellMaterialMoveTitle = rowMaterialMoveTitle.createCell(k);
							cellMaterialMoveTitle.setCellStyle(csdt);
							cellMaterialMoveTitle.setCellValue(EnumMaterielMoveColumnName.getColumnName(k));
							moveSheet.setColumnWidth(k,
									EnumMaterielMoveColumnName.getColumnName(k).getBytes().length * 2 * 256);
						}
						// 创建数据列表，并设置其单元格格式
						for (int j = 0; j < materialMoves.size(); j++) {
							HSSFRow rowMaterialMoveData = moveSheet.createRow((short) j + 2);
							rowMaterialMoveData.setHeight((short) 300);
							for (int k = 0; k < 5; k++) {
								HSSFCell cellMaterialMoveData = rowMaterialMoveData.createCell(k);
								cellMaterialMoveData
								.setCellValue(EnumMaterielMoveColumnName.getMethod(k, materialMoves.get(j)));
								cellMaterialMoveData.setCellStyle(csdd);
								moveSheet.setColumnWidth(j,
										EnumMaterielMoveColumnName.getMethod(k, materialMoves.get(j)).getBytes().length * 2
										* 256);
							}
						}
					}
					sheet.autoSizeColumn(x);
				} else {
					cell.setCellValue(EnumPackingListMaterielColumnName.getMethod(x, packingListMateriels.get(i)));
					sheet.autoSizeColumn(x);
				}
			}
		}
		return workbook;
	}

	// 手动添加箱单物料关系
	@RequestMapping("/savePackingListMateriel")
	@ResponseBody
	public JSONObject savePackingListMateriel(BtPackingListMateriel packingListMateriel) {
		JSONObject result = new JSONObject();
		String planId = packingListService.lookPackingList(packingListMateriel.getPackingListId()).getPlanId();
		List<String> materielQrcode = packingListMaterielService
				.checkMaterielQrcodeOnlyByCompanyId(UserContext.get().getCompanyId());
		if (StringUtils.isEmpty(packingListMateriel.getMaterielCode())) {
			result.put("flag", false);
			result.put("msg", "请选择物料!");
			return result;
		}
		if (StringUtils.isEmpty(packingListMateriel.getMaterielAmount())) {
			result.put("flag", false);
			result.put("msg", "请输入物料数量!");
			return result;
		}
		if (StringUtils.isEmpty(packingListMateriel.getTakePhoto())) {
			result.put("flag", false);
			result.put("msg", "请选择是否强制拍照!");
			return result;
		}
		if (StringUtils.isEmpty(packingListMateriel.getMaterielAmount())) {
			try {
				int number = packingListMateriel.getMaterielAmount();
			} catch (Exception e) {
				e.printStackTrace();
				result.put("flag", false);
				result.put("msg", "物料数量为非数字");
				return result;
			}

		}
		// 校验物料是否存在.
		BtMateriel materiel = materielService.getMaterielByMaterielCode(packingListMateriel.getMaterielCode(),
				UserContext.get().getCompanyId());
		if (materiel == null) {
			result.put("flag", false);
			result.put("msg", "未找到相应编码的物料,请核对后重新添加!");
			return result;
		}
		// 根据数量添加记录条数.
		int amount = packingListMateriel.getMaterielAmount();
		if (amount > 1) {
			int count = 0;
			for (int i = 0; i < amount; i++) {
				BtPackingListMateriel btPackingListMateriel = new BtPackingListMateriel();
				String id = UUID.get();
				btPackingListMateriel.setId(id);
				btPackingListMateriel.setMaterielQrcode(EnumScanType.MATERIEL.getValue() + ";" + id);
				btPackingListMateriel.setMaterielAmount(1);
				btPackingListMateriel.setMaterielCode(packingListMateriel.getMaterielCode());
				if (!StringUtils.isEmpty(materiel)) {
					btPackingListMateriel.setMaterielId(materiel.getId());
					btPackingListMateriel.setMaterielName(materiel.getMaterielName());
				}
				btPackingListMateriel.setPackingListId(packingListMateriel.getPackingListId());
				btPackingListMateriel.setPackingListCode(packingListMateriel.getPackingListCode());
				btPackingListMateriel.setTakePhoto(packingListMateriel.getTakePhoto());

				btPackingListMateriel.setCreateTime(new Date());
				btPackingListMateriel.setCompanyId(UserContext.get().getCompanyId());
				packingListMaterielService.addPackingListMateriel(btPackingListMateriel);
				count += 1;
			}

			if (count == amount) {
				result.put("flag", true);
				result.put("msg", "操作成功");
				return result;
			} else {
				result.put("flag", false);
				result.put("msg", "操作失败.请重试!");
				return result;
			}
		} else {
			BtPackingListMateriel btPackingListMateriel = new BtPackingListMateriel();
			String id = UUID.get();
			btPackingListMateriel.setId(id);
			if (StringUtils.isEmpty(packingListMateriel.getMaterielQrcode())) {
				btPackingListMateriel.setMaterielQrcode(EnumScanType.MATERIEL.getValue() + ";" + id);
			} else {
				if (materielQrcode.contains(packingListMateriel.getMaterielQrcode())) {
					result.put("flag", false);
					result.put("msg", "二维码信息" + packingListMateriel.getMaterielQrcode() + "已经存在,请确保二维码在公司中的唯一性");
					return result;
				} else {
					btPackingListMateriel.setMaterielQrcode(packingListMateriel.getMaterielQrcode());
				}
			}
			btPackingListMateriel.setMaterielAmount(1);
			btPackingListMateriel.setMaterielCode(packingListMateriel.getMaterielCode());
			if (!StringUtils.isEmpty(materiel)) {
				btPackingListMateriel.setMaterielId(materiel.getId());
				btPackingListMateriel.setMaterielName(materiel.getMaterielName());
			}
			btPackingListMateriel.setPackingListId(packingListMateriel.getPackingListId());
			btPackingListMateriel.setPackingListCode(packingListMateriel.getPackingListCode());
			btPackingListMateriel.setTakePhoto(packingListMateriel.getTakePhoto());

			btPackingListMateriel.setCreateTime(new Date());
			btPackingListMateriel.setCompanyId(UserContext.get().getCompanyId());
			String checkId = packingListMaterielService.addPackingListMateriel(btPackingListMateriel);
			if (checkId != null) {
				result.put("flag", true);
				result.put("msg", "操作成功");
				return result;
			} else {
				result.put("flag", false);
				result.put("msg", "操作失败.请重试!");
				return result;
			}
		}

	}

	// 删除记录
	@RequestMapping("/deletePackingListMateriel/{id}")
	@ResponseBody
	public JSONObject deletePackingListMateriel(@PathVariable("id") String id) {
		JSONObject result = new JSONObject();
		int count = packingListMaterielService.deletePackingListMateriel(id);
		if (count == 1) {
			result.put("flag", true);
			result.put("msg", "操作成功!");
			return result;
		} else {
			result.put("flag", false);
			result.put("msg", "操作失败请重试!");
			return result;
		}
	}

	// 分页
	@Override
	public PageQuery<? extends BaseInfo> getQueryList(PageQuery<? extends BaseInfo> pageQuery) {
		@SuppressWarnings("unchecked")
		Map<String, Object> map = (Map<String, Object>) pageQuery.getParas();
		if (StringUtils.isEmpty(map.get("packingListId"))) {
			map.put("packingListId", null);
		} else {
			map.put("packingListId", map.get("packingListId"));
		}
		map.put("companyId", UserContext.get().getCompanyId());
		if (StringUtils.isEmpty(pageQuery.getOrderBy())) {
			pageQuery.setOrderBy("materiel_name  desc,create_time asc");
		}
		pageQuery.setPageSize(5);
		return packingListMaterielService.getQueryList(pageQuery);
	}

	@Override
	public boolean isQueryAll() {
		return true;
	}

}
